#!/bin/bash
# Rust 环境安装和 moparse 编译测试脚本

set -e

echo "=========================================="
echo "Rust 版本 moparse 编译测试脚本"
echo "=========================================="
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 步骤 1: 检查 Rust 是否已安装
print_step "1. 检查 Rust 环境"
if command -v rustc &> /dev/null; then
    print_info "Rust 已安装"
    rustc --version
    cargo --version
else
    print_warn "Rust 未安装"
    echo ""
    echo "请执行以下命令安装 Rust:"
    echo "  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
    echo ""
    echo "安装完成后，执行:"
    echo "  source \$HOME/.cargo/env"
    echo "  $0"
    exit 1
fi

echo ""

# 步骤 2: 进入项目目录
print_step "2. 进入项目目录"
cd /home/apachee/trunk/Crystal/CrystalFlowAnalyzer/modb/moparse-rs
print_info "当前目录: $(pwd)"

echo ""

# 步骤 3: 检查项目结构
print_step "3. 检查项目结构"
if [ -f "Cargo.toml" ]; then
    print_info "✓ Cargo.toml 存在"
else
    print_error "✗ Cargo.toml 不存在"
    exit 1
fi

if [ -f "build.rs" ]; then
    print_info "✓ build.rs 存在"
else
    print_error "✗ build.rs 不存在"
    exit 1
fi

if [ -d "src" ]; then
    print_info "✓ src/ 目录存在"
    echo "  源文件:"
    ls -1 src/*.rs | sed 's/^/    /'
else
    print_error "✗ src/ 目录不存在"
    exit 1
fi

echo ""

# 步骤 4: 检查依赖
print_step "4. 检查依赖和配置"
print_info "Cargo.toml 内容摘要:"
head -20 Cargo.toml | sed 's/^/  /'

echo ""

# 步骤 5: 清理旧的编译产物
print_step "5. 清理旧的编译产物"
if [ -d "target" ]; then
    print_info "清理 target/ 目录..."
    cargo clean
    print_info "清理完成"
else
    print_info "无需清理（首次编译）"
fi

echo ""

# 步骤 6: 编译 debug 版本
print_step "6. 编译 debug 版本（用于测试）"
print_info "开始编译..."
if cargo build 2>&1 | tee /tmp/cargo_build.log; then
    print_info "✓ Debug 版本编译成功"
    
    if [ -f "target/debug/moparse" ]; then
        print_info "可执行文件: target/debug/moparse"
        ls -lh target/debug/moparse
    fi
else
    print_error "✗ 编译失败"
    echo ""
    echo "错误日志:"
    tail -50 /tmp/cargo_build.log
    exit 1
fi

echo ""

# 步骤 7: 运行基本测试
print_step "7. 运行基本测试"

print_info "测试 1: 显示版本信息"
./target/debug/moparse --version || print_warn "版本信息显示失败"

echo ""

print_info "测试 2: 显示帮助信息"
./target/debug/moparse --help | head -20 || print_warn "帮助信息显示失败"

echo ""

# 步骤 8: 测试解析功能（如果有测试文件）
print_step "8. 测试解析功能"

TEST_FILE="../tests/counter_full.v"
if [ -f "$TEST_FILE" ]; then
    print_info "找到测试文件: $TEST_FILE"
    
    print_info "测试解析 Verilog 文件..."
    if ./target/debug/moparse parse -v "$TEST_FILE" -o /tmp/test_output.modb 2>&1; then
        print_info "✓ 解析成功"
        
        if [ -f "/tmp/test_output.modb" ]; then
            print_info "输出文件大小: $(ls -lh /tmp/test_output.modb | awk '{print $5}')"
            
            print_info "测试显示模块信息..."
            ./target/debug/moparse show -s /tmp/test_output.modb || true
            
            rm -f /tmp/test_output.modb
        fi
    else
        print_warn "解析测试失败（可能功能未完全实现）"
    fi
else
    print_warn "测试文件 $TEST_FILE 不存在，跳过解析测试"
fi

echo ""

# 步骤 9: 编译 release 版本（可选）
print_step "9. 编译 release 版本（优化）"
read -p "是否编译 release 版本？ (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    print_info "开始编译 release 版本..."
    if cargo build --release 2>&1 | tee /tmp/cargo_release.log; then
        print_info "✓ Release 版本编译成功"
        
        if [ -f "target/release/moparse" ]; then
            print_info "可执行文件: target/release/moparse"
            ls -lh target/release/moparse
            
            # 检查依赖
            if command -v ldd &> /dev/null; then
                print_info "动态库依赖:"
                ldd target/release/moparse | sed 's/^/  /'
            fi
        fi
    else
        print_error "✗ Release 编译失败"
        tail -50 /tmp/cargo_release.log
    fi
else
    print_info "跳过 release 编译"
fi

echo ""

# 步骤 10: 总结
print_step "10. 编译测试总结"
echo ""
echo "=========================================="
echo "编译测试完成！"
echo "=========================================="
echo ""
echo "可执行文件位置:"
echo "  Debug 版本:   target/debug/moparse"
[ -f "target/release/moparse" ] && echo "  Release 版本: target/release/moparse"
echo ""
echo "使用示例:"
echo "  # 查看帮助"
echo "  ./target/debug/moparse --help"
echo ""
echo "  # 解析 Verilog 文件"
echo "  ./target/debug/moparse parse -v input.v -o output.modb"
echo ""
echo "  # 显示模块信息"
echo "  ./target/debug/moparse show -s output.modb -v"
echo ""
echo "  # 显示层次结构"
echo "  ./target/debug/moparse hierarchy -i output.modb -m module_name"
echo ""

print_info "如需在 CentOS 7 上部署，请参考 CENTOS7_DEPLOYMENT.md"
